#file:/Applications/2024/fk-project/src/views/Login/index.vue
<template>
  <div class="login-container">
    <h2>登录</h2>
    <form @submit.prevent="handleLogin">
      <div class="form-group">
        <label for="username">用户名:</label>
        <input type="text" id="username" v-model="username" required />
      </div>
      <div class="form-group">
        <label for="password">密码:</label>
        <input type="password" id="password" v-model="password" required />
      </div>
      <button type="submit">登录</button>
    </form>
    <p v-if="error" class="error">{{ error }}</p>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { setToken } from '@/utils/auth'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'
import { login } from "@/api/index.ts"

const router = useRouter();
const username = ref('admin');
const password = ref('123456');
const error = ref('');

const handleLogin = async () => {
  try {
    // 这里可以添加你的登录逻辑，比如调用 API 验证用户
    if (username.value && password.value) {
      await login({ username: username.value, password: password.value }).then((res: any) => {
        console.log(res);
        // 登录成功，将 token 存储在 localStorage
        if (res.code === 200) {
          ElMessage({
            message: res.data.msg,
            type: 'success',
            duration: 5 * 1000
          })
          setToken(res.data.token)
          localStorage.setItem('token', res.data.token);
          router.push('/');
        }
      });
    } else {
      error.value = '用户名或密码错误';
    }
  } catch (err) {
    error.value = '登录失败，请重试';
  }
};
</script>

<style lang="scss" scoped>
.login-container {
  min-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

.error {
  color: red;
  text-align: center;
}
</style>